/**
 * Result.java [V 1.0.0]
 * classes : com.xiaocq.wordsgod.Result
 * xiaocq Create at 2012-7-16 下午1:42:16
 */
package com.xiaocq.wordsgod;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xiaocq.wordsgod.db.DataGenerateCenter;
import com.xiaocq.wordsgod.model.Control;
import com.xiaocq.wordsgod.model.Vocabulary;

/**
 * com.xiaocq.wordsgod.Result
 * 
 * @author Mystory Create at 2012-7-16 下午1:42:16
 */
public class Result extends Activity {
	private LinearLayout navigator;
	private Button backToMenu, restart;
	private TextView title;

	private ListView wrongSet;

	private TextView timeCost, wordsCount, hitRate, level;

	private Control mControl;

	private List<Vocabulary> wordList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.result);

		Intent intent = getIntent();
		mControl = Control.convertToControl(intent);
		initComponents();

		HandleTask task = new HandleTask();
		task.execute();
	}

	private void initComponents() {
		navigator = (LinearLayout) findViewById(R.id.result_navigator);
		backToMenu = (Button) navigator.findViewById(R.id.nav_leftBtn);
		title = (TextView) navigator.findViewById(R.id.nav_middleText);
		restart = (Button) navigator.findViewById(R.id.nav_rightBtn);

		wrongSet = (ListView) findViewById(R.id.result_wrongSet);

		timeCost = (TextView) findViewById(R.id.result_timeCost);
		wordsCount = (TextView) findViewById(R.id.result_wordsCount);
		hitRate = (TextView) findViewById(R.id.result_hitRate);
		level = (TextView) findViewById(R.id.result_level);
		
		backToMenu.setText(R.string.backToMenu);
		title.setText("测试结果");
		restart.setText(R.string.restart);
		
		backToMenu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				saveAndQuit();
			}
		});
		
		restart.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mControl.resetTest();
				Intent intent = mControl.convertToIntent();
				intent.setClass(Result.this, WordTest.class);
				startActivity(intent);
				finish();
			}
		});

	}

	private class HandleTask extends AsyncTask<Void, Integer, Void> {
		private ProgressDialog progressDialog;
		private DataGenerateCenter dataGenerateCenter;
		private int[] wordScore;
		private int size;
		@Override
		protected Void doInBackground(Void... params) {
			int index = 0;
			Vocabulary vocabulary;

			dataGenerateCenter.createCursor();
			dataGenerateCenter.updateWordState(wordScore);
			for (int i : wordScore) {
				if (i % 10 == 0) {
					System.out.println(i);
					vocabulary = dataGenerateCenter.wrapVocabulary((i / 10),
							Control.COMPLETION);
					wordList.add(vocabulary);

					publishProgress(index++);
				}
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dataGenerateCenter = new DataGenerateCenter(mControl, Result.this);
			size = mControl.getWrongCount();
			wordList = new ArrayList<Vocabulary>(size);
			wordScore = mControl.getWordScore();

			progressDialog = new ProgressDialog(Result.this);
			progressDialog.setMessage(getText(R.string.i_am_parsing));
			progressDialog.setMax(size);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			dataGenerateCenter.close();
			
			setGradeTable();
			
			CostumAdapter adapter = new CostumAdapter(Result.this, wordList);
			wrongSet.setAdapter(adapter);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			progressDialog.setProgress(values[0]);
		}
	}
	
	private void saveAndQuit(){
		mControl.clearTest(getSharedPreferences(Control.PREF_NAME, MODE_PRIVATE));
		finish();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			saveAndQuit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void setGradeTable(){
		int correctNum = mControl.getCorrectNum();
		int totalNum = mControl.getTotalNum();
		long totalTestTime = mControl.getTotalTestTime();
		double hitRateValue = correctNum == 0 ? 0.00 : (correctNum * 1.0 / totalNum) * 100;
		
		timeCost.setText(getTimeCost(totalTestTime));
		wordsCount.setText(getWordsCount(correctNum, totalNum));
		hitRate.setText(getHitRate(hitRateValue));
		level.setText(getLevel(hitRateValue));
	}
	
	private String getTimeCost(long timeCost){
		long second = timeCost / 1000L;
		long minute = second / 60L;
		second = second % 60L;
		long hour = minute / 60L;
		minute = minute % 60L;
		
		String time = "耗时：";
		
		if(hour != 0){
			time += (hour + " 小时");
		}else if((minute != 0) && (minute == 0 && hour != 0)){
			time += (minute + " 分钟 ");
		}else if(second != 0){
			time += (second + " 秒");
		}
		return time;
	}
	
	private String getWordsCount(int correctNum, int totalNum){
		String wordsCount = "总共：";
		wordsCount += (totalNum + "题\n");
		wordsCount += ("答对：" + correctNum + "题");
		
		return wordsCount;
	}
	
	private String getHitRate(double hitRateValue){
		String hitRate = "命中率：";
		hitRate += String.format("%1$-4.2f", hitRateValue);
		hitRate += "%";
		
		return hitRate;
	}
	
	private String getLevel(double hitRateValue){
		if(hitRateValue >= 100.00){
			return "S";
		}else if(hitRateValue >= 95.00){
			return "A+";
		}else if(hitRateValue >= 85.00){
			return "A";
		}else if(hitRateValue >= 80.00){
			return "B";
		}else if(hitRateValue >= 70.00){
			return "C";
		}else if(hitRateValue >= 60.00){
			return "D";
		}else{
			return "E";
		}
	}
}
